package wendyeq.iweb.blog.util;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;

import org.apache.log4j.Logger;

public final class JdoManager {

	private static final Logger logger = Logger.getLogger(JdoManager.class);

	private static final ThreadLocal<PersistenceManager> session = new ThreadLocal<PersistenceManager>();

	private static final PersistenceManagerFactory pmfInstance = JDOHelper
			.getPersistenceManagerFactory("transactions-optional");

	private JdoManager() {
	}

	public static PersistenceManager getSession() {
		PersistenceManager sess = session.get();
		if (sess == null || sess.isClosed()) {
			logger.debug("create new session");
			sess = getPMF().getPersistenceManager();
			session.set(sess);
		} else {
			logger.debug("return existent session");
		}
		return sess;
	}

	public static void closeSession() {
		PersistenceManager sess = session.get();

		if (sess != null) {
			logger.debug("close session");
			session.set(null);
			if (!sess.isClosed()) {
				sess.close();
			}
		}
	}

	private static PersistenceManagerFactory getPMF() {
		return pmfInstance;
	}
}
